package com.oceansoft.mobile.econsole.modules.check.service.impl;

import cn.jpush.api.push.PushResult;
import com.alibaba.fastjson.JSON;
import com.oceansoft.mobile.econsole.cache.redis.CacheBaseService;
import com.oceansoft.mobile.econsole.common.util.MD5Util;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.check.entity.IdNumCheck;
import com.oceansoft.mobile.econsole.modules.check.entity.VehicleCheck;
import com.oceansoft.mobile.econsole.modules.check.persistence.ICheckMapper;
import com.oceansoft.mobile.econsole.modules.check.service.ICheckService;
import com.oceansoft.mobile.econsole.modules.message.bizz.V3Handler;
import com.oceansoft.mobile.econsole.modules.message.entity.MessageContent;
import com.oceansoft.mobile.econsole.modules.message.entity.PushMessage;
import com.oceansoft.mobile.econsole.modules.message.persistence.IMessageMapper;
import com.oceansoft.mobile.econsole.modules.message.util.Utils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

/**
 * Created by Administrator on 2016/2/2.
 */
@Service
public class CheckServiceImpl extends CacheBaseService implements ICheckService {

    Logger logger = Logger.getLogger(CheckServiceImpl.class);

    @Resource
    private ICheckMapper checkMapper;

    @Resource
    private IMessageMapper messageMapper;

    @Override
    @Transactional
    public Result saveIdNumCheck(IdNumCheck idNumCheck) {

        // redis中是否已存在
        IdNumCheck cacheIdNumCheck = super.getObject(MD5Util.getMD5String(idNumCheck.getIdNum()), IdNumCheck.class);

        if(null != cacheIdNumCheck && StringUtils.isNotBlank(cacheIdNumCheck.getName())){
            return new Result(Result.SUCC,cacheIdNumCheck,"身份证号核查信息获取");
        }

        int count = checkMapper.countIdNumCheck(idNumCheck.getIdNum());
        if(count >= 1){
            return new Result(Result.SUCC,"身份证号核查提交成功");
        }

        idNumCheck.setId(UUID.randomUUID().toString());
        int rt = checkMapper.saveIdNumCheck(idNumCheck);
        if(rt > 0){
            return new Result(Result.SUCC,"身份证号核查提交成功");
        }
        return new Result(Result.FAILURE,"身份证号核查提交失败");
    }

    @Override
    @Transactional
    public Result saveVehicleCheck(VehicleCheck vehicleCheck) {
        // redis中是否已存在
        VehicleCheck cacheVehicleCheck = super.getObject(MD5Util.getMD5String(vehicleCheck.getVehicleNum()), VehicleCheck.class);

        if(null != cacheVehicleCheck && StringUtils.isNotBlank(cacheVehicleCheck.getVehicleInfo())){
            return new Result(Result.SUCC,cacheVehicleCheck,"车牌号核查信息获取");
        }

        int count = checkMapper.countVehicleCheck(vehicleCheck.getVehicleNum());
        if(count >= 1){
            return new Result(Result.SUCC,"车牌号核查提交成功");
        }

        vehicleCheck.setId(UUID.randomUUID().toString());
        int rt = checkMapper.saveVehicleCheck(vehicleCheck);
        if(rt > 0){
            return new Result(Result.SUCC,"车牌号核查提交成功");
        }
        return new Result(Result.FAILURE,"车牌号核查提交失败");
    }

    @Override
    @Transactional
    public Result pushIdNumCheck(String guid) {
        IdNumCheck idNumCheck = checkMapper.getIdNumCheckByGuid(guid);

        if(null != idNumCheck){
            //缓存
            super.set(MD5Util.getMD5String(idNumCheck.getIdNum()), JSON.toJSONString(idNumCheck));
            return pushIdNumCheckMessage(idNumCheck);
        }else {
            return new Result(Result.FAILURE);
        }
    }

    @Override
    @Transactional
    public Result pushVehicleNumCheck(String guid) {
        VehicleCheck vehicleCheck = checkMapper.getVehicleNumCheckByGuid(guid);

        if(null != vehicleCheck){
            //缓存
            super.set(MD5Util.getMD5String(vehicleCheck.getVehicleNum()), JSON.toJSONString(vehicleCheck));
            return pushVehicleNumCheckMessage(vehicleCheck);
        }else {
            return new Result(Result.FAILURE);
        }
    }

    private Result pushIdNumCheckMessage(IdNumCheck idNumCheck){
        String content = "";
        String messageGroup = "";
        PushMessage message = null;

        // 针对个人推送
        PushMessage.PushType pushType = PushMessage.PushType.lookUp(3);

        content = new MessageContent("身份证号核查", idNumCheck.getName()+"+"+idNumCheck.getGender(), -1, "").toJson();//-1:系统通知
        if (pushType.equals(PushMessage.PushType.BROADCAST)) {
            message = new PushMessage(Utils.getCurrNo(), pushType.getType(), "", content, "test");
        } else if (pushType.equals(PushMessage.PushType.GROUP)) {
            if (org.springframework.util.StringUtils.isEmpty(messageGroup)) {
                return new Result(Result.FAILURE,"缺少群组名称");
            }
            message = new PushMessage(Utils.getCurrNo(), pushType.getType(), messageGroup, content, "test");
        } else if (pushType.equals(PushMessage.PushType.ALIAS)) {
            if (org.springframework.util.StringUtils.isEmpty(idNumCheck.getMemberId())) {
                return new Result(Result.FAILURE,"缺少别名");
            }
            message = new PushMessage(Utils.getCurrNo(), pushType.getType(), idNumCheck.getMemberId(), content, "test");
        } else {
            return new Result(Result.FAILURE,"发送对象错误");
        }
        if (message != null) {
            message.setCreate_time(new Date());
            message.setPlatform("2");//ALL平台

            try {
                logger.info("开始推送身份证号核查结果:" + idNumCheck.getIdNum());

                V3Handler handler = new V3Handler(message);
                PushResult result = handler.push();

                logger.info("=====>result:"+result);
                if(result.msg_id == 0 || result.sendno == 0){
                    logger.info("=====消息推送失败: "+ idNumCheck.getIdNum());
                    message.setIs_send(0);//推送失败
                    messageMapper.add(message);
                    return new Result(Result.FAILURE,"消息推送失败");
                }else{
                    //保存推送消息
                    message.setIs_send(1);//已推送
                    messageMapper.add(message);
                    return new Result(Result.SUCC,"消息推送成功");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(Result.FAILURE,"异常");
            }

        }

        return new Result(Result.FAILURE,"异常");
    }

    private Result pushVehicleNumCheckMessage(VehicleCheck vehicleCheck){
        String content = "";
        String messageGroup = "";
        PushMessage message = null;

        // 针对个人推送
        PushMessage.PushType pushType = PushMessage.PushType.lookUp(3);

        content = new MessageContent("车牌号核查", vehicleCheck.getName()+"+"+vehicleCheck.getIdNum()+"+"+vehicleCheck.getVehicleInfo(), -1, "").toJson();//-1:系统通知
        if (pushType.equals(PushMessage.PushType.BROADCAST)) {
            message = new PushMessage(Utils.getCurrNo(), pushType.getType(), "", content, "test");
        } else if (pushType.equals(PushMessage.PushType.GROUP)) {
            if (org.springframework.util.StringUtils.isEmpty(messageGroup)) {
                return new Result(Result.FAILURE,"缺少群组名称");
            }
            message = new PushMessage(Utils.getCurrNo(), pushType.getType(), messageGroup, content, "test");
        } else if (pushType.equals(PushMessage.PushType.ALIAS)) {
            if (org.springframework.util.StringUtils.isEmpty(vehicleCheck.getMemberId())) {
                return new Result(Result.FAILURE,"缺少别名");
            }
            message = new PushMessage(Utils.getCurrNo(), pushType.getType(), vehicleCheck.getMemberId(), content, "test");
        } else {
            return new Result(Result.FAILURE,"发送对象错误");
        }
        if (message != null) {
            message.setCreate_time(new Date());
            message.setPlatform("2");//ALL平台

            try {
                logger.info("开始推送车牌号核查结果:" + vehicleCheck.getVehicleNum());

                V3Handler handler = new V3Handler(message);
                PushResult result = handler.push();

                logger.info("=====>result:"+result);
                if(result.msg_id == 0 || result.sendno == 0){
                    logger.info("=====消息推送失败: "+ vehicleCheck.getVehicleNum());
                    message.setIs_send(0);//推送失败
                    messageMapper.add(message);
                    return new Result(Result.FAILURE,"消息推送失败");
                }else{
                    //保存推送消息
                    message.setIs_send(1);//已推送
                    messageMapper.add(message);
                    return new Result(Result.SUCC,"消息推送成功");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(Result.FAILURE,"异常");
            }

        }

        return new Result(Result.FAILURE,"异常");
    }
}
